package live.ifox.base;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import live.ifox.helper.CommonHelper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static live.ifox.helper.CommonHelper.JSON_TYPE;

public abstract class BaseRestActivity extends AppCompatActivity {
    protected String entry;
    protected String baseUrl;
    protected OkHttpClient client;
    protected ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        actionBar = getSupportActionBar();
        if (actionBar != null)
            // 给左上角图标的左边加上一个返回的图标,对应ActionBar.DISPLAY_HOME_AS_UP
            actionBar.setDisplayHomeAsUpEnabled(true);
        client = new OkHttpClient();
    }

    public boolean do_copyItem(JSONObject object, String column) {
        String detail = object.getString(column);
        if (detail == null || detail.isEmpty())
            return false;

        CommonHelper.setClipboardText(this, entry, detail);
        CommonHelper.showMessage(this, "已复制到剪贴板");
        return true;
    }

    public boolean do_removeItem(JSONObject object) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确定操作").setMessage("确定删除吗？");
        builder.setPositiveButton("确定",
                (paramAnonymousDialogInterface, paramAnonymousInt) ->
                {
                    int id = object.getIntValue("id");
                    if (id > 0)
                        httpGet(baseUrl + "remove/" + id);
                });

        builder.setNegativeButton("取消",
                (paramAnonymousDialogInterface, paramAnonymousInt) -> {
                });

        builder.create().show();
        return true;
    }

    public boolean do_updateItem(JSONObject object, String key, Object value) {
        int id = object.getIntValue("id");
        if (id == 0)
            return false;

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put(key, value);
        httpPost(baseUrl + "update", JSON.toJSONString(map));
        return true;
    }

    public boolean checkPermission(String permission) {
        int result = ActivityCompat.checkSelfPermission(this,
                permission);
        return result == PackageManager.PERMISSION_GRANTED;
    }

    public void requestPermission(String[] permissions, int requestCode) {
        ActivityCompat.requestPermissions(this,
                permissions, requestCode);
    }

    public void httpGet(String url) {
        Request request = new Request.Builder()
                .url(url)
                .get() //默认就是GET请求，可以不写
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                CommonHelper.debug("HTTP GET ERROR!");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String reply = response.body().string();
                runOnUiThread(() -> onReceivedReply(reply));
            }
        });
    }

    public void httpPost(String url, String json) {
        RequestBody body = RequestBody.create(JSON_TYPE, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                CommonHelper.debug("HTTP PUT ERROR!");
            }

            @Override
            public void onResponse(Call call, Response response) {
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void onReceivedReply(String reply) {
        try {
            JSONObject object = JSON.parseObject(reply);
            if (object != null && !object.isEmpty())
                processReply(object);
        } catch (JSONException e) {
            CommonHelper.debug("ERROR: 错误的JSON格式！");
        }
    }

    public abstract void processReply(JSONObject rootObject);
}
